package lib

import (
	"bytes"
	"errors"
	"fmt"
	"strings"

	"github.com/tealeg/xlsx"
)

func generateCSVFromXLSXFile(excelFileName string, delimiter string, sheetIndex int) (err error, buf *bytes.Buffer) {
	xlFile, err := xlsx.OpenFile(excelFileName)
	if err != nil {
		return err, nil
	}
	sheetLen := len(xlFile.Sheets)
	switch {
	case sheetLen == 0:
		return errors.New("This XLSX file contains no sheets."), nil
	case sheetIndex >= sheetLen:
		return errors.New(fmt.Sprintf("No sheet %d available, please select a sheet between 0 and %d\n", sheetIndex, sheetLen-1)), nil
	}
	sheet := xlFile.Sheets[sheetIndex]
	buf = bytes.NewBufferString("")
	for _, row := range sheet.Rows {
		var vals []string
		if row != nil {
			for _, cell := range row.Cells {

				format := cell.GetNumberFormat()
				if strings.EqualFold(format, "mm-dd-yy") {
					cell.NumFmt = "yyyy/mm/dd"
				}
				str, err := cell.FormattedValue()
				if err != nil {
					vals = append(vals, err.Error())
				}
				vals = append(vals, fmt.Sprintf("%q", str))
			}
			buf.WriteString(strings.Join(vals, delimiter))
			buf.WriteString("\n")
		}
	}
	return nil, buf
}
